<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Control 12 Lights via MQTT with Icons</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        body {
            font-family: 'Arial', sans-serif;
            background-color: #2c3e50;
            color: white;
            margin: 0;
            padding: 10px;
        }

        .lights-container {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            /* 使用gap代替margin-left/margin-bottom */
        }

        .light-card {
            width: calc(33.333% - 20px);
            /* 每行三个卡片，减去gap */
            min-width: 100px;
            /* 最小宽度以适应小屏幕 */
            max-width: 150px;
            /* 设置最大宽度 */
            height: auto;
            /* 自动高度 */
            background-color: rgba(0, 0, 0, 0.2);
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
            transition: transform 0.2s ease-in-out;
        }

        @media (max-width: 768px) {
            .light-card {
                width: calc(50% - 10px);
                /* 在平板上每行两个卡片 */
            }

            .lights-container {
                display: flex;
                flex-wrap: wrap;
                justify-content: center;
                /* 居中显示 */
                gap: 10px;
                /* 使用gap代替margin-left/margin-bottom */
            }
        }

        @media (max-width: 480px) {
            .light-card {
                width: 100%;
                /* 在手机上每行一个卡片 */
            }
        }

        .light-card:hover {
            transform: translateY(-5px);
        }

        .light {
            padding-top: 100%;
            /* 维持正方形比例 */
            position: relative;
        }

        .light i {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            font-size: 3.5rem;
            transition: color 0.3s ease-in-out;
            cursor: pointer;
        }

        .light.off i {
            color: #ccc;
        }

        .light.on i {
            color: gold;
            text-shadow: 0 0 15px gold, 0 0 20px gold, 0 0 30px gold;
        }
    </style>
</head>

<body>
    <div class="lights-container" id="lightsContainer"></div>

    <script>
        // 灯光对象数组
        const lights = Array.from({
            length: 12
        }, (_, i) => ({
            id: (i + 1).toString(),
            state: 'off',
            iconClass: 'fas fa-lightbulb'
        }));

        // 动态创建灯光元素并初始化
        const container = document.getElementById('lightsContainer');
        const throttleTime = 500; // 节流的时间间隔（毫秒）
        let lightTimers = {}; // 用于存储各个灯光的计时器

        lights.forEach(light => {
            const card = document.createElement('div');
            card.className = 'light-card';

            const lightDiv = document.createElement('div');
            lightDiv.id = `light-${light.id}`;
            lightDiv.className = `light ${light.state}`;

            const icon = document.createElement('i');
            icon.className = `${light.iconClass}`;

            lightDiv.appendChild(icon);
            card.appendChild(lightDiv);
            container.appendChild(card);

            // 绑定点击事件，并应用节流
            let isThrottled = false;
            lightDiv.addEventListener('click', async (event) => {
                if (isThrottled) return;

                try {
                    isThrottled = true;
                    await toggleLight(light, lightDiv);
                } finally {
                    // 设置一个短暂的延迟，之后允许再次触发点击事件
                    lightTimers[light.id] = setTimeout(() => {
                        isThrottled = false;
                    }, throttleTime);
                }
            });
        });

        async function toggleLight(light, lightDiv) {
            try {
                // 切换灯光状态
                light.state = light.state === 'on' ? 'off' : 'on';
                lightDiv.classList.toggle('on');
                lightDiv.classList.toggle('off');

                // 发送请求到服务器
                const response = await fetch('http://914cc47.r26.cpolar.top/api/publish', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        topic: `test`,
                        message: light.state === 'on' ? 'a' + light.id : 'b' + light.id
                    })
                });

                if (!response.ok) {
                    console.error('Failed to publish message');
                    alert('Failed to publish message');
                }
            } catch (error) {
                console.error('Error during publishing:', error);
                alert('An error occurred while trying to publish the message.');
            } finally {
                // 确保即使发生错误也解除节流限制
                clearTimeout(lightTimers[light.id]);
                delete lightTimers[light.id];
            }
        }
    </script>
</body>

</html>